// index.js
import {
  get,
  post
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
// 获取应用实例
const app = getApp()

Page({
  data: {
    currentShopIndex: 1,
    btns: ['充值管理', '优惠管理'],
    currentBtn: 0,
    tabs: ['使用中', '已失效'],
    tabIndex: 0,
    orderList: [],
    shopInfo: {},
  },
  onShow() {
    this.getSwitch();
  },
  getSwitch() {
    const {
      currentBtn,
      tabIndex,
      currentShopIndex
    } = this.data;
    if (currentBtn === 0) {
      this.getRecharge(currentShopIndex, tabIndex);
    } else if (currentBtn === 1) {
      this.getDiscount(currentShopIndex, tabIndex);
    }
  },
  getRecharge(shop, used = 0) {
    get(APIS.recharge, {
      shop,
      used
    }).then(res => {
      const list = res.data;
      this.setData({
        orderList: list.map(x => {
          return {
            ...x,
            title: `充值${x.amount}元 送${x.presentation}元`,
            rule: `充值${x.amount}元 送${x.presentation}元`,
            time: `${x.start} ~ ${x.end}`
          }
        })
      });
    })
  },
  getDiscount(shop, used = 0) {
    get(APIS.discount, {
      shop,
      used
    }).then(res => {
      const list = res.data;
      this.setData({
        orderList: list.map(x => {
          return {
            ...x,
            title: x.alias,
            rule: x.alias,
            time: `${x.start} ~ ${x.end}`
          }
        })
      });
    })
  },
  handleJump(e) {
    let {
      info
    } = e.currentTarget.dataset;
    console.log(info);
    wx.navigateTo({
      url: `/pages/distribution/index?id=${info.id}`
    })
  },
  handleTab(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      currentBtn: index,
      tabIndex: 0
    }, () => {
      this.getSwitch();
    });
  },
  handleJumpCreate(e) {
    const {
      type
    } = e.target.dataset;
    wx.navigateTo({
      url: `/pages/create/index?type=${type}`
    })
  },
  handleChange(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      tabIndex: index,
    }, () => {
      this.getSwitch();
    });
  },
  handleShopIndex(e) {
    const currentShopIndex = e.detail;
    this.setData({
      currentShopIndex
    }, () => {
      this.getSwitch();
    });
  },
  handleJumpDetail(e) {
    const {
      item
    } = e.target.dataset;
    const {
      used,
      id
    } = item;
    wx.navigateTo({
      url: `/pages/detail/index?type=${this.data.currentBtn}&id=${id}`
    })
  },
})